# coding: utf-8
import sys

import pandas as pd
from PySide6.QtCore import Qt
from PySide6.QtWidgets import QApplication, QHeaderView, QTableWidgetItem, QWidget, QHBoxLayout

from qfluentwidgets import TableWidget


class Information(QWidget):

    def __init__(self, parent=None, df:pd.DataFrame=None):
        super().__init__(parent)

        self.hBoxLayout = QHBoxLayout(self)
        self.tableView = TableWidget(self)

        # enable border
        self.tableView.setBorderVisible(True)
        self.tableView.setBorderRadius(8)

        self.tableView.setWordWrap(False)

        self.tableView.verticalHeader().hide()
        self.tableView.resizeColumnsToContents()
        # self.tableView.horizontalHeader().setSectionResizeMode(QHeaderView.Stretch)
        # self.tableView.setSortingEnabled(True)

        self.setStyleSheet("Demo{background: rgb(255, 255, 255)} ")
        self.hBoxLayout.setContentsMargins(50, 30, 50, 30)
        self.hBoxLayout.addWidget(self.tableView)
        self.resize(1000, 800)
        
        # 将 DataFrame 加载到 QTableWidget
        if df is not None:
            self.loadDataFrameToTableWidget(df)

    def loadDataFrameToTableWidget(self, df:pd.DataFrame):
        # 设置行数和列数
        self.tableView.setRowCount(df.shape[0])
        self.tableView.setColumnCount(df.shape[1])

        # 设置列标题
        self.tableView.setHorizontalHeaderLabels(df.columns)

        # 填充数据
        if df.empty:
            self.tableView.setRowCount(0)
            return

        for row in range(df.shape[0]):
            for col in range(df.shape[1]):
                # content = str(df.iat[row, col]).replace('\n', '').replace('\r', '')
                content = str(df.iat[row, col])
                item = QTableWidgetItem(content)
                item.setTextAlignment(Qt.AlignCenter)
                self.tableView.setItem(row, col, item)

        # 设置列宽根据内容自动调整
        header = self.tableView.horizontalHeader()
        header.setSectionResizeMode(QHeaderView.Stretch)

    def readTableData(self):
        # 获取行数和列数
        row_count = self.tableView.rowCount()
        col_count = self.tableView.columnCount()

        # 获取列标题
        headers = [self.tableView.horizontalHeaderItem(i).text() for i in range(col_count)]

        # 创建一个字典来存储数据
        data = {header: [] for header in headers}

        # 遍历每个单元格，获取内容
        for row in range(row_count):
            for col in range(col_count):
                item = self.tableView.item(row, col)
                data[headers[col]].append(item.text() if item else '')

        # 转换为 DataFrame
        df = pd.DataFrame(data)
        return df

if __name__ == "__main__":
    app = QApplication(sys.argv)
    w = Information()
    w.show()
    app.exec()